package com.whsxt.controller;

import com.github.pagehelper.PageInfo;
import com.whsxt.common.AjaxResult;
import com.whsxt.domain.Role;
import com.whsxt.dto.RoleDto;
import com.whsxt.service.RoleService;
import com.whsxt.utils.Result2DTreeVoUtils;
import com.whsxt.vo.BaseDtreeVo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

/**
 * 角色接口
 */
@RestController
@RequestMapping("/role")
@RequiresRoles(value = {"admin", "test"}, logical = Logical.OR)
public class RoleController {

    @Autowired
    private RoleService roleService;

    /**
     * 加载分页查询数据
     * @param roleDto
     * @return
     */
    @RequestMapping("/findByPage.do")
    public AjaxResult findByPage(RoleDto roleDto) {

        PageInfo<Role> rolePageInfo = roleService.findPage(roleDto);

        return AjaxResult.ok(rolePageInfo);
    }

    /**
     * 新增角色数据
     * @param roleDto
     * @return
     */
    @RequestMapping("/add.do")
    @RequiresPermissions("role:add")
    public AjaxResult add(RoleDto roleDto){
        boolean isOk = roleService.save(roleDto);
        return isOk ? AjaxResult.ok(): AjaxResult.error("新增角色数据失败");
    }

    @RequestMapping("/delete.do")
    @RequiresPermissions("role:delete")
    public AjaxResult delete(Integer[] id){
        boolean isOk = roleService.batchRemove(Arrays.asList(id));
        return isOk ? AjaxResult.ok() : AjaxResult.error("删除角色数据失败");
    }

    @RequestMapping("/update.do")
    @RequiresRoles("role:update")
    public AjaxResult update(RoleDto roleDto){
        boolean isOk = roleService.update(roleDto);
        return isOk? AjaxResult.ok() : AjaxResult.error("修改角色失败");
    }

    /**
     * 加载角色树的数据
     * @param userId
     * @return
     */
    @RequestMapping("/loadRolesTree.do")
    public AjaxResult loadRolesTree(Integer userId){
        // 先查询所有的角色集合
        List<Role> roles = roleService.loadRoles();
        // 然后通过该用户自身的id 在查询出自已所有的角色 id(此步的操作是为了方便回显数据)
        List<Integer> userRoleIds = roleService.selectRoleIdsByUserId(userId);
        // 使用工具类转化数据
        List<BaseDtreeVo> rolesDtree =  Result2DTreeVoUtils.roles2Dtree(roles, userRoleIds);
        return AjaxResult.ok(rolesDtree);
    }

    /**
     * 为角色授予权限
     * @param roleId
     * @param permIds
     * @return
     */
    @RequestMapping("/assign.do")
    @RequiresRoles("admin")
    public AjaxResult assign(Integer roleId, Integer[] permIds){
        boolean isOk = roleService.assign(roleId, permIds);
        return isOk? AjaxResult.ok():AjaxResult.error("角色授权失败");
    }
}
